package com.bittech.servlet.smallfileserver.service.impl;

import com.bittech.servlet.smallfileserver.common.Page;
import com.bittech.servlet.smallfileserver.dao.SmallFileDao;
import com.bittech.servlet.smallfileserver.dao.StorageModeFactory;
import com.bittech.servlet.smallfileserver.domain.SmallFile;
import com.bittech.servlet.smallfileserver.service.FileService;
import com.bittech.servlet.smallfileserver.web.config.listener.StorageModeLoaderListener;
import org.apache.commons.codec.digest.DigestUtils;
import org.bson.types.ObjectId;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * Author: secondriver
 * Created: 2018/8/27
 */
public class FileServiceImpl implements FileService {
    
    private final SmallFileDao smallFileDao ;
 
    public FileServiceImpl() {
        this.smallFileDao = StorageModeFactory.getSmallDao(StorageModeLoaderListener.storageMode);
    }
    
    @Override
    public SmallFile saveFile(SmallFile smallFile) {
        //Id生成策略
        //UUID
        //时间戳+自增长的编号
        //开源的一些实现 ObjectId , twitter
        smallFile.setId(new ObjectId().toString());
        smallFile.setUploadDate(LocalDateTime.now());
        smallFile.setMd5(DigestUtils.md5Hex(smallFile.getContent().getData()));
        smallFileDao.save(smallFile);
        return smallFile;
    }
    
    @Override
    public void removeFile(String id) {
        smallFileDao.delete(id);
    }
    
    @Override
    public Optional<SmallFile> getFileById(String id) {
        return Optional.ofNullable(smallFileDao.find(id));
    }
    
    @Override
    public List<SmallFile> listFilesByPage(int pageIndex, int pageSize) {
        return smallFileDao.query(new Page(pageIndex, pageSize));
    }
}
